<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { addWatermark, removeWatermark } from '@/utils/common/watermark'
import html2canvas from 'html2canvas'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { checkStudentWeeklyApi, getStudentWeeklyDetailApi } from '@/api/job'
// /引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
//引入相关样式
import '@vue-office/docx/lib/index.css'
import VueOfficePdf from '@vue-office/pdf'
import { showStatusMessage } from '@/utils/common/showMessage'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const detailData = ref({})
const type = ref('')
const officeType = ref('')
function getDetailData() {
  detailData.value = history.state.data ? JSON.parse(history.state.data) : ''
  type.value = history.state.type
  console.log(type.value)
  console.log(detailData.value)

  // jobDetail

  if (type.value == 'studentMaterial') {
    officeType.value = detailData.value.split('.').pop()
  }
  if (type.value == 'studentEmploymentMaterial') {
    officeType.value = detailData.value.split('.').pop()
  }

  if (type.value == 'previewResume') {
    officeType.value = detailData.value.split('.').pop()
  }
}
getDetailData()
const weeklyData = ref({})
async function getWeeklyData() {
  try {
    const res = await getStudentWeeklyDetailApi({
      account: detailData.value.account,
      weekly: detailData.value.weekly
    })
    weeklyData.value = res.data
    console.log('周记数据:', weeklyData.value)
  } catch (error) {
    console.error('获取周记数据失败:', error)
  }
}
function getDetailWeekly() {
  switch (type.value) {
    case 'weeklyDetail':
      getWeeklyData()
      break

    default:
      break
  }
}
getDetailWeekly()

function addWatermarkType() {
  switch (type.value) {
    case 'weeklyDetail':
      addWatermark(
        `${detailData.value.account} ${detailData.value.name} ${detailData.value.weekly}周记`
      )
      break

    default:
      break
  }
}
function titleShow(type) {
  let title = ''
  switch (type) {
    case 'weeklyJournalDetail':
      title = '周记详情'
      break
    case 'studentMaterial':
      title = '实习材料'
      break
    case 'jobDetail':
      title = '职位详情'
      break
    case 'studentEmploymentMaterial':
      title = '实习材料'
      break
    default:
      break
  }
  return title
}
onMounted(() => {
  addWatermarkType()
})

// 在组件销毁前移除水印
onBeforeUnmount(() => {
  removeWatermark()
})
function routerBack() {
  router.go(-1)
}
// 获取
async function checkStudentWeekly(value) {
  loading.value = true
  try {
    const res = await checkStudentWeeklyApi({
      id: detailData.value.id,
      status: value
    })
    showStatusMessage(res)
    getWeeklyData()
    loading.value = false
  } catch (error) {
    loading.value = false
  }
}
console.log(type.value)

// 添加审核方法
function handleApprove() {
  // TODO: 调用审核通过接口
  switch (type.value) {
    case 'weeklyDetail':
      checkStudentWeekly(2)
      break

    default:
      break
  }
  // routerBack()
}

function handleReject() {
  // TODO: 调用驳回接口
  switch (type.value) {
    case 'weeklyDetail':
      checkStudentWeekly(1)
      break

    default:
      break
  }
  // routerBack()
}
// 导出为图片
async function handlePrintImage() {
  try {
    // 获取要截图的DOM元素
    //.student-detail为一个dom容器，是需要导出为图片的dom
    const element = document.querySelector('.info-card')
    if (!element) {
      ElMessage.error('获取页面元素失败')
      return
    }

    ElMessage.info('正在生成图片，请稍候...')

    // 使用html2canvas截图
    const canvas = await html2canvas(element, {
      useCORS: true, // 允许加载跨域图片
      scale: 2, // 提高图片质量
      backgroundColor: '#ffffff' // 设置白色背景
    })

    // 将canvas转为图片
    const image = canvas.toDataURL('image/png')

    // 创建下载链接
    const link = document.createElement('a')
    link.href = image
    link.download = `学生周记-${detailData.value.name}-${new Date().getTime()}.png`

    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('图片已成功导出')
  } catch (error) {
    console.error('生成图片失败:', error)
    ElMessage.error('生成图片失败，请重试')
  }
}
// 下载文件
function handleDownloadFile() {
  // window.open(detailData.value, '_blank')
  // 下载文件
  const link = document.createElement('a')
  link.href = detailData.value
  link.download = detailData.value.split('/').pop()
  link.click()
  ElMessage.success('文件已下载')

}
onMounted(() => {
  loading.value = false
})
</script>

<template>
  <div class="student-detail" v-loading="loading">
    <div class="header">
      <el-button @click="routerBack" icon="ArrowLeft">返回</el-button>
      <el-button
        v-if="type == 'weeklyJournalDetail'"
        type="primary"
        @click="handlePrintImage"
        :icon="Document"
        class="print-btn"
      >
        导出图片
      </el-button>
      <h2>{{ titleShow(type) }}</h2>
    </div>

    <div v-if="type === 'weeklyDetail'" class="info-card">
      <el-card>
        <template #header>
          <div class="card-header">
            <h3>基本信息</h3>
          </div>
        </template>
        <el-descriptions :column="2">
          <el-descriptions-item label="学号">{{ weeklyData.account }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ weeklyData.name }}</el-descriptions-item>
          <el-descriptions-item label="班级">{{ weeklyData.class }}</el-descriptions-item>
          <el-descriptions-item label="周次">{{ weeklyData.weekly }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ weeklyData.create_time }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag
              :type="
                weeklyData.status === 0 ? 'warning' : weeklyData.status === 2 ? 'success' : 'danger'
              "
            >
              {{
                weeklyData.status === 0 ? '待审核' : weeklyData.status === 2 ? '已通过' : '已驳回'
              }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card class="status-card">
        <template #header>
          <div class="card-header">
            <h3>本周完成工作</h3>
          </div>
        </template>
        <div v-html="weeklyData.task"></div>
      </el-card>

      <el-card class="status-card">
        <template #header>
          <div class="card-header">
            <h3>下周工作计划</h3>
          </div>
        </template>
        <div v-html="weeklyData.plan"></div>
      </el-card>

      <div class="action-buttons" v-if="weeklyData.status === 0">
        <el-button type="success" @click="handleApprove">通过</el-button>
        <el-button type="danger" @click="handleReject">驳回</el-button>
      </div>
    </div>
    <div v-if="type === 'studentMaterial' || type === 'studentEmploymentMaterial' || type === 'previewResume'" class="info-card">
      <el-card class="document-viewer">
        <template #header>
          <div class="viewer-header">
            <h3>{{ type === 'studentMaterial' ? '实习材料预览' : type === 'studentEmploymentMaterial' ? '就业材料预览' : '简历预览' }}</h3>
          </div>
        </template>

        <div class="document-container">
          <template v-if="officeType === 'doc'">
            <div class="doc-warning">
              <el-alert
                title="暂不支持预览doc格式文件"
                type="warning"
                description="请下载后查看文件内容"
                show-icon
                :closable="false"
              />
              <el-button 
                type="primary" 
                @click="handleDownloadFile"
                class="download-btn"
                icon="Download"
              >
                下载文件
              </el-button>
            </div>
          </template>
          <vue-office-docx
            v-else-if="officeType === 'docx'"
            :src="detailData"
            class="document-content"
            @rendered="renderedHandler"
            @error="errorHandler"
            style="height: 80vh"
          />
          <vue-office-pdf
            v-else-if="officeType === 'pdf'"
            :src="detailData"
            class="document-content"
            @rendered="renderedHandler"
            @error="errorHandler"
            style="height: 80vh"
          />
          <img 
            v-else-if="['png', 'jpg', 'jpeg'].includes(officeType)" 
            :src="detailData" 
            alt="预览图片"
            class="preview-image" 
          />
          <el-alert
            v-else
            title="不支持的文件格式"
            type="error"
            description="仅支持预览 docx、pdf、png、jpg、jpeg 格式的文件"
            show-icon
            :closable="false"
          />
        </div>
      </el-card>
    </div>
    <div v-if="type === 'jobDetail'" class="info-card">
      <el-card>
        <template #header>
          <div class="card-header">
            <h3>职位信息</h3>
          </div>
        </template>
        <el-descriptions :column="2">
          <el-descriptions-item label="企业名称">{{
            detailData.enterpriseName
          }}</el-descriptions-item>
          <el-descriptions-item label="职位名称">{{ detailData.jobName }}</el-descriptions-item>
          <el-descriptions-item label="薪资">{{ detailData.salary }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ detailData.phone }}</el-descriptions-item>
          <el-descriptions-item label="工作地点">{{ detailData.jobLocation }}</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{
            detailData.jobDetailLocation
          }}</el-descriptions-item>
          <el-descriptions-item label="发布时间">{{ detailData.create_time }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="detailData.status === '2' ? 'success' : 'warning'">
              {{ detailData.status === '2' ? '已通过' : '待审核' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-card class="status-card">
          <template #header>
            <div class="card-header">
              <h3>职位描述</h3>
            </div>
          </template>
          <div>{{ detailData.jobDesc }}</div>
        </el-card>

        <el-card class="status-card">
          <template #header>
            <div class="card-header">
              <h3>任职要求</h3>
            </div>
          </template>
          <div>{{ detailData.jobRequire }}</div>
        </el-card>
      </el-card>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.student-detail {
  padding: 20px;

  .header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .print-btn {
      margin-left: 10px;
    }

    h2 {
      margin-left: 20px;
      margin-bottom: 0;
    }
  }

  .info-card {
    max-width: 1000px;
    margin: 0 auto;

    :deep(.el-descriptions__content) {
      text-align: left;
    }
  }

  .status-card {
    max-width: 1000px;
    margin: 20px auto;

    :deep(.el-card__body) {
      text-align: left;
    }
  }

  .card-header {
    text-align: left;
    h3 {
      margin: 0;
    }
  }

  .action-buttons {
    max-width: 1000px;
    margin: 20px auto;
    text-align: left;

    .el-button {
      margin: 0 10px 0 0;
    }
  }

  .doc-warning {
    padding: 20px;
    text-align: center;

    .download-btn {
      margin-top: 20px;
    }
  }

  .preview-image {
    max-width: 100%;
    height: auto;
    margin: 0 auto;
    display: block;
  }
}
</style>
